package co.edu.usbcali.pqr.presentation.backingBeans;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

import org.primefaces.component.commandbutton.CommandButton;
import org.primefaces.component.inputtext.InputText;
import org.primefaces.component.selectonemenu.SelectOneMenu;
import org.primefaces.context.RequestContext;
import org.primefaces.event.RowEditEvent;

import co.edu.usbcali.pqr.exceptions.ZMessManager;
import co.edu.usbcali.pqr.modelo.AnxsXArea;
import co.edu.usbcali.pqr.modelo.dto.AnexosPqrDTO;
import co.edu.usbcali.pqr.modelo.dto.AnxsXAreaDTO;
import co.edu.usbcali.pqr.modelo.dto.AreasInvolucradasDTO;
import co.edu.usbcali.pqr.presentation.businessDelegate.IBusinessDelegatorView;
import co.edu.usbcali.pqr.presentation.dataModel.AnxsXAreaDataModel;
import co.edu.usbcali.pqr.presentation.dataModel.AreasInvolucradasDataModel;
import co.edu.usbcali.pqr.utilities.FacesUtils;


@ManagedBean
@ViewScoped
public class AnxsXAreaView implements Serializable {
    private static final long serialVersionUID = 1L;
    private SelectOneMenu txtEsObligatorio;
    private SelectOneMenu txtIdAnexoPqr_AnexosPqr;
    private InputText txtIdAreaInvolucrada_AreasInvolucradas;
    private InputText txtIdAnxXArea;
    private CommandButton btnSave;
    private CommandButton btnModify;
    private CommandButton btnDelete;
    private CommandButton btnClear;
    private CommandButton btnCrear;
    private List<AnxsXAreaDTO> data;
    private List<AreasInvolucradasDTO> dataArea;
    private AnxsXAreaDTO selectedAnxsXArea;
    private AreasInvolucradasDTO selectedArea;
    private AnxsXArea entity;
    private AreasInvolucradasDataModel areaDataModel;
    private AnxsXAreaDataModel anxsXAreaDataModel;
    private boolean showDialog;
    @ManagedProperty(value = "#{BusinessDelegatorView}")
    private IBusinessDelegatorView businessDelegatorView;
	private Map<String, Long> anexos = new HashMap<String, Long>();

    /////////////////////////////////////////
		
	public String cambiarObligatorio(){
		
		try {
			entity=businessDelegatorView.getAnxsXArea(selectedAnxsXArea.getIdAnxXArea());
			
			if(entity.getEsObligatorio().equals("S")){
				entity.setEsObligatorio("N");
			}else{
				entity.setEsObligatorio("S");
			}
			
			businessDelegatorView.updateAnxsXArea(entity);
			  
			editar();

	            RequestContext.getCurrentInstance().update("form:tabla2");
	            FacesUtils.addInfoMessage("La Obligatoriedad del anexo fue cambiada con exito");
			
		} catch (Exception e) {

			e.printStackTrace();
		}
		
		return "";
	}
	
	public String eliminarAnexo(){
		
		try {
			entity=businessDelegatorView.getAnxsXArea(selectedAnxsXArea.getIdAnxXArea());
			businessDelegatorView.deleteAnxsXArea(entity);
			
            data=businessDelegatorView.anexosXIdArea(selectedArea.getIdAreaInvolucrada());
            
            if(data.size()>=1){
            	anxsXAreaDataModel=new AnxsXAreaDataModel(data);
            	selectedAnxsXArea=data.get(0);
                
            }else{
            	anxsXAreaDataModel=new AnxsXAreaDataModel();
            }
            RequestContext.getCurrentInstance().update("form:tabla2");
            FacesUtils.addInfoMessage("El Anexo se elimino con exito");
			
		} catch (Exception e) {

		}
		
		return "";
	}
	
	
		//Limpia los campos, Habilita los botones de Crear y Modificar
		public void cerrar() {

			txtEsObligatorio.setDisabled(true);
			txtIdAnexoPqr_AnexosPqr.setDisabled(true);
			
			txtEsObligatorio.setValue(null);
			txtIdAnexoPqr_AnexosPqr.setValue(null);
			
			//init();
			//btnSave.setDisabled(true);
			btnModify.setDisabled(false);
			//btnCrear.setDisabled(false);
		}
	
	
		//Coloca los datos del DTO seleccionado en las variables de Binding txt
		public String editar() {

			try {

				data=businessDelegatorView.anexosXIdArea(selectedArea.getIdAreaInvolucrada());
				anxsXAreaDataModel=new AnxsXAreaDataModel(data);
				
				modificar();

			} catch (Exception e) {
				if (selectedArea == null) {
					btnCrear.setDisabled(true);
					cerrar();
					FacesUtils
							.addErrorMessage("Seleccione Area a Modificar");
				}else{
					System.out.println(e.getMessage());
				}
			}
			return "";
		}	
    
		//Habilita los campos y desabilita el boton Modificar
		public String modificar() {

			txtEsObligatorio.setDisabled(false);
			txtIdAnexoPqr_AnexosPqr.setDisabled(false);

			btnSave.setDisabled(false);
			btnModify.setDisabled(true);

			return "";
		}	
  
		
		public String guardar(){
			
			try {
	            entity = new AnxsXArea();

	            entity.setEsObligatorio(FacesUtils.checkString(txtEsObligatorio));
	            entity.setAnexosPqr(businessDelegatorView.getAnexosPqr(FacesUtils.checkLong(txtIdAnexoPqr_AnexosPqr)));
	            entity.setAreasInvolucradas(businessDelegatorView.getAreasInvolucradas(selectedArea.getIdAreaInvolucrada()));
	            
	            businessDelegatorView.saveAnxsXArea(entity);
	            
	            data=businessDelegatorView.anexosXIdArea(selectedArea.getIdAreaInvolucrada());
				anxsXAreaDataModel=new AnxsXAreaDataModel(data);
	            RequestContext.getCurrentInstance().update("form:tabla2");
	            FacesUtils.addInfoMessage("El anexo se agrego con exito");
				
			} catch (Exception e) {

				System.out.println(e.getMessage());
				
			}
			
			
			return "";
		}

    ////////////////////////////////////////
    
    public AnxsXAreaView() {
        super();
    }

    public void rowEventListener(RowEditEvent e) {
        try {
            AnxsXAreaDTO anxsXAreaDTO = (AnxsXAreaDTO) e.getObject();

            if (txtEsObligatorio == null) {
                txtEsObligatorio = new SelectOneMenu();
            }

            txtEsObligatorio.setValue(anxsXAreaDTO.getEsObligatorio());

            if (txtIdAnexoPqr_AnexosPqr == null) {
                txtIdAnexoPqr_AnexosPqr = new SelectOneMenu();
            }

            txtIdAnexoPqr_AnexosPqr.setValue(anxsXAreaDTO.getIdAnexoPqr_AnexosPqr());

            if (txtIdAreaInvolucrada_AreasInvolucradas == null) {
                txtIdAreaInvolucrada_AreasInvolucradas = new InputText();
            }

            txtIdAreaInvolucrada_AreasInvolucradas.setValue(anxsXAreaDTO.getIdAreaInvolucrada());

            if (txtIdAnxXArea == null) {
                txtIdAnxXArea = new InputText();
            }

            txtIdAnxXArea.setValue(anxsXAreaDTO.getIdAnxXArea());

            Long idAnxXArea = FacesUtils.checkLong(txtIdAnxXArea);
            entity = businessDelegatorView.getAnxsXArea(idAnxXArea);

            action_modify();
        } catch (Exception ex) {
        }
    }

    public String action_new() {
        action_clear();
        selectedAnxsXArea = null;
        setShowDialog(true);

        return "";
    }

    public String action_clear() {
        entity = null;
        selectedAnxsXArea = null;

        if (txtEsObligatorio != null) {
            txtEsObligatorio.setValue(null);
            txtEsObligatorio.setDisabled(true);
        }

        if (txtIdAnexoPqr_AnexosPqr != null) {
            txtIdAnexoPqr_AnexosPqr.setValue(null);
            txtIdAnexoPqr_AnexosPqr.setDisabled(true);
        }

        if (txtIdAreaInvolucrada_AreasInvolucradas != null) {
            txtIdAreaInvolucrada_AreasInvolucradas.setValue(null);
            txtIdAreaInvolucrada_AreasInvolucradas.setDisabled(true);
        }

        if (txtIdAnxXArea != null) {
            txtIdAnxXArea.setValue(null);
            txtIdAnxXArea.setDisabled(false);
        }

        if (btnSave != null) {
            btnSave.setDisabled(true);
        }

        if (btnDelete != null) {
            btnDelete.setDisabled(true);
        }

        return "";
    }

    public void listener_txtId() {
        try {
            Long idAnxXArea = FacesUtils.checkLong(txtIdAnxXArea);
            entity = (idAnxXArea != null)
                ? businessDelegatorView.getAnxsXArea(idAnxXArea) : null;
        } catch (Exception e) {
            entity = null;
        }

        if (entity == null) {
            txtEsObligatorio.setDisabled(false);
            txtIdAnexoPqr_AnexosPqr.setDisabled(false);
            txtIdAreaInvolucrada_AreasInvolucradas.setDisabled(false);
            txtIdAnxXArea.setDisabled(false);
            btnSave.setDisabled(false);
        } else {
            txtEsObligatorio.setValue(entity.getEsObligatorio());
            txtEsObligatorio.setDisabled(false);
            txtIdAnexoPqr_AnexosPqr.setValue(entity.getAnexosPqr()
                                                   .getIdAnexoPqr());
            txtIdAnexoPqr_AnexosPqr.setDisabled(false);
            txtIdAreaInvolucrada_AreasInvolucradas.setValue(entity.getAreasInvolucradas()
                                                                  .getIdAreaInvolucrada());
            txtIdAreaInvolucrada_AreasInvolucradas.setDisabled(false);
            txtIdAnxXArea.setValue(entity.getIdAnxXArea());
            txtIdAnxXArea.setDisabled(true);
            btnSave.setDisabled(false);

            if (btnDelete != null) {
                btnDelete.setDisabled(false);
            }
        }
    }

    public String action_edit(ActionEvent evt) {
        selectedAnxsXArea = (AnxsXAreaDTO) (evt.getComponent().getAttributes()
                                               .get("selectedAnxsXArea"));
        txtEsObligatorio.setValue(selectedAnxsXArea.getEsObligatorio());
        txtEsObligatorio.setDisabled(false);
        txtIdAnexoPqr_AnexosPqr.setValue(selectedAnxsXArea.getIdAnexoPqr_AnexosPqr());
        txtIdAnexoPqr_AnexosPqr.setDisabled(false);
        txtIdAreaInvolucrada_AreasInvolucradas.setValue(selectedAnxsXArea.getIdAreaInvolucrada());
        txtIdAreaInvolucrada_AreasInvolucradas.setDisabled(false);
        txtIdAnxXArea.setValue(selectedAnxsXArea.getIdAnxXArea());
        txtIdAnxXArea.setDisabled(true);
        btnSave.setDisabled(false);
        setShowDialog(true);

        return "";
    }

    public String action_save() {
        try {
            if ((selectedAnxsXArea == null) && (entity == null)) {
                action_create();
            } else {
                action_modify();
            }

            data = null;
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_create() {
        try {
            entity = new AnxsXArea();

            Long idAnxXArea = FacesUtils.checkLong(txtIdAnxXArea);

            entity.setEsObligatorio(FacesUtils.checkString(txtEsObligatorio));
            entity.setIdAnxXArea(idAnxXArea);
            entity.setAnexosPqr((FacesUtils.checkLong(txtIdAnexoPqr_AnexosPqr) != null)
                ? businessDelegatorView.getAnexosPqr(FacesUtils.checkLong(
                        txtIdAnexoPqr_AnexosPqr)) : null);
            entity.setAreasInvolucradas((FacesUtils.checkLong(
                    txtIdAreaInvolucrada_AreasInvolucradas) != null)
                ? businessDelegatorView.getAreasInvolucradas(
                    FacesUtils.checkLong(txtIdAreaInvolucrada_AreasInvolucradas))
                : null);
            businessDelegatorView.saveAnxsXArea(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYSAVED);
            action_clear();
        } catch (Exception e) {
            entity = null;
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modify() {
        try {
            if (entity == null) {
                Long idAnxXArea = new Long(selectedAnxsXArea.getIdAnxXArea());
                entity = businessDelegatorView.getAnxsXArea(idAnxXArea);
            }

            entity.setEsObligatorio(FacesUtils.checkString(txtEsObligatorio));
            entity.setAnexosPqr((FacesUtils.checkLong(txtIdAnexoPqr_AnexosPqr) != null)
                ? businessDelegatorView.getAnexosPqr(FacesUtils.checkLong(
                        txtIdAnexoPqr_AnexosPqr)) : null);
            entity.setAreasInvolucradas((FacesUtils.checkLong(
                    txtIdAreaInvolucrada_AreasInvolucradas) != null)
                ? businessDelegatorView.getAreasInvolucradas(
                    FacesUtils.checkLong(txtIdAreaInvolucrada_AreasInvolucradas))
                : null);
            businessDelegatorView.updateAnxsXArea(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
        } catch (Exception e) {
            data = null;
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_delete_datatable(ActionEvent evt) {
        try {
            selectedAnxsXArea = (AnxsXAreaDTO) (evt.getComponent()
                                                   .getAttributes()
                                                   .get("selectedAnxsXArea"));

            Long idAnxXArea = new Long(selectedAnxsXArea.getIdAnxXArea());
            entity = businessDelegatorView.getAnxsXArea(idAnxXArea);
            action_delete();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_delete_master() {
        try {
            Long idAnxXArea = FacesUtils.checkLong(txtIdAnxXArea);
            entity = businessDelegatorView.getAnxsXArea(idAnxXArea);
            action_delete();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public void action_delete() throws Exception {
        try {
            businessDelegatorView.deleteAnxsXArea(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED);
            action_clear();
            data = null;
        } catch (Exception e) {
            throw e;
        }
    }

    public String action_closeDialog() {
        setShowDialog(false);
        action_clear();

        return "";
    }

    public String actionDeleteDataTableEditable(ActionEvent evt) {
        try {
            selectedAnxsXArea = (AnxsXAreaDTO) (evt.getComponent()
                                                   .getAttributes()
                                                   .get("selectedAnxsXArea"));

            Long idAnxXArea = new Long(selectedAnxsXArea.getIdAnxXArea());
            entity = businessDelegatorView.getAnxsXArea(idAnxXArea);
            businessDelegatorView.deleteAnxsXArea(entity);
            data.remove(selectedAnxsXArea);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modifyWitDTO(String esObligatorio, Long idAnxXArea,
        Long idAnexoPqr_AnexosPqr, Long idAreaInvolucrada_AreasInvolucradas)
        throws Exception {
        try {
            entity.setEsObligatorio(FacesUtils.checkString(esObligatorio));
            businessDelegatorView.updateAnxsXArea(entity);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
        } catch (Exception e) {
            //renderManager.getOnDemandRenderer("AnxsXAreaView").requestRender();
            FacesUtils.addErrorMessage(e.getMessage());
            throw e;
        }

        return "";
    }

    public SelectOneMenu getTxtEsObligatorio() {
        return txtEsObligatorio;
    }

    public void setTxtEsObligatorio(SelectOneMenu txtEsObligatorio) {
        this.txtEsObligatorio = txtEsObligatorio;
    }

    public SelectOneMenu getTxtIdAnexoPqr_AnexosPqr() {
        return txtIdAnexoPqr_AnexosPqr;
    }

    public void setTxtIdAnexoPqr_AnexosPqr(SelectOneMenu txtIdAnexoPqr_AnexosPqr) {
        this.txtIdAnexoPqr_AnexosPqr = txtIdAnexoPqr_AnexosPqr;
    }

    public InputText getTxtIdAreaInvolucrada_AreasInvolucradas() {
        return txtIdAreaInvolucrada_AreasInvolucradas;
    }

    public void setTxtIdAreaInvolucrada_AreasInvolucradas(
        InputText txtIdAreaInvolucrada_AreasInvolucradas) {
        this.txtIdAreaInvolucrada_AreasInvolucradas = txtIdAreaInvolucrada_AreasInvolucradas;
    }

    public InputText getTxtIdAnxXArea() {
        return txtIdAnxXArea;
    }

    public void setTxtIdAnxXArea(InputText txtIdAnxXArea) {
        this.txtIdAnxXArea = txtIdAnxXArea;
    }

    public List<AnxsXAreaDTO> getData() {
        try {
            if (data == null) {
                data = businessDelegatorView.getDataAnxsXArea();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }

    public void setData(List<AnxsXAreaDTO> anxsXAreaDTO) {
        this.data = anxsXAreaDTO;
    }

    public AnxsXAreaDTO getSelectedAnxsXArea() {
        return selectedAnxsXArea;
    }

    public void setSelectedAnxsXArea(AnxsXAreaDTO anxsXArea) {
        this.selectedAnxsXArea = anxsXArea;
    }

    public CommandButton getBtnSave() {
        return btnSave;
    }

    public void setBtnSave(CommandButton btnSave) {
        this.btnSave = btnSave;
    }

    public CommandButton getBtnModify() {
        return btnModify;
    }

    public void setBtnModify(CommandButton btnModify) {
        this.btnModify = btnModify;
    }

    public CommandButton getBtnDelete() {
        return btnDelete;
    }

    public void setBtnDelete(CommandButton btnDelete) {
        this.btnDelete = btnDelete;
    }

    public CommandButton getBtnClear() {
        return btnClear;
    }

    public void setBtnClear(CommandButton btnClear) {
        this.btnClear = btnClear;
    }

    public TimeZone getTimeZone() {
        return java.util.TimeZone.getDefault();
    }

    public IBusinessDelegatorView getBusinessDelegatorView() {
        return businessDelegatorView;
    }

    public void setBusinessDelegatorView(
        IBusinessDelegatorView businessDelegatorView) {
        this.businessDelegatorView = businessDelegatorView;
    }

    public boolean isShowDialog() {
        return showDialog;
    }

    public void setShowDialog(boolean showDialog) {
        this.showDialog = showDialog;
    }

	public AreasInvolucradasDTO getSelectedArea() {
    	if(selectedArea==null){
    		try {
    			selectedArea=getDataArea().get(0);
			} catch (Exception e) {
			} 
    	}
		return selectedArea;
	}

	public void setSelectedArea(AreasInvolucradasDTO selectedArea) {
		this.selectedArea = selectedArea;
	}

	public AreasInvolucradasDataModel getAreaDataModel() {
		areaDataModel=new AreasInvolucradasDataModel(getDataArea());
		return areaDataModel;
	}

	public void setAreaDataModel(AreasInvolucradasDataModel areaDataModel) {
		this.areaDataModel = areaDataModel;
	}

	public List<AreasInvolucradasDTO> getDataArea() {
		try {
			if(dataArea==null){
				dataArea=businessDelegatorView.getDataAreasInvolucradas();	
			}
		} catch (Exception e) {
		}
		return dataArea;
	}

	public void setDataArea(List<AreasInvolucradasDTO> dataArea) {
		this.dataArea = dataArea;
	}

	public CommandButton getBtnCrear() {
		return btnCrear;
	}

	public void setBtnCrear(CommandButton btnCrear) {
		this.btnCrear = btnCrear;
	}


	public Map<String, Long> getAnexos() {

		try {
			List<AnexosPqrDTO> dataAnexo = businessDelegatorView.getDataAnexosPqr();
			for (int i = 0; i < dataAnexo.size(); i++) {
				if(dataAnexo.get(i).getEstadoRegistro().equals("A")){
					anexos.put(dataAnexo.get(i).getDescripcionAnexo(), dataAnexo.get(i).getIdAnexoPqr());
				}
			}
		} catch (Exception e) {

		}
		
		return anexos;
	}


	public void setAnexos(Map<String, Long> anexos) {
		this.anexos = anexos;
	}


	public AnxsXAreaDataModel getAnxsXAreaDataModel() {
		return anxsXAreaDataModel;
	}


	public void setAnxsXAreaDataModel(AnxsXAreaDataModel anxsXAreaDataModel) {
		this.anxsXAreaDataModel = anxsXAreaDataModel;
	}
	
	
	
}
